package com.miku.blog.utils;

import com.miku.blog.domain.pojo.SystemConstance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author shkstart
 * @create ${}YEAR-06-17 0:32
 */

@Slf4j
public class EmailUtils {


    private static final String SYMBOLS = "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ";
    private static final Random RANDOM = new SecureRandom();


    public static String sendEmail(JavaMailSender javaMailSender, String to, String nickName, String startTime, String endTime) {

        JavaMailSenderImpl javaMailSenderImpl = (JavaMailSenderImpl) javaMailSender;

        MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        try {

            messageHelper.setFrom(SystemConstance.EMAIL_FROM_NAME + "<" + javaMailSenderImpl.getUsername() + ">");
            messageHelper.setTo(to);
            messageHelper.setSubject(SystemConstance.BLOG_NAME);
            messageHelper.setSentDate(DateUtils.parseToCN(startTime));

            String verCode = generateCode();

            messageHelper.setText(EmailHtmlTemplateUtils.generateEmailTemplate(SystemConstance.BLOG_NAME,
                    nickName,
                    verCode,
                    startTime,
                    endTime,
                    String.valueOf((SystemConstance.CODE_VALIDITY_TIME / (60 * 1000)))),
                    true);

            javaMailSenderImpl.send(mimeMessage);
            return verCode;
        } catch (MessagingException e) {
            log.error(">>>>> 发送邮箱验证码异常 <<<<<", e);
            log.error(">>>>> END <<<<<" + System.lineSeparator());
        }
        return null;
    }


    /**
     * 生成一个6位验证码
     *
     * @return
     */
    public static String generateCode() {

        char[] chars = new char[6];

        for (int i = 0; i < chars.length; i++) {
            char charAt = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
            chars[i] = charAt;
        }

        return new String(chars);
    }


    /**
     * 检查是否为邮箱   或  邮箱格式是否正确
     *
     * @return
     */
    public static boolean checkEmail(String email) {
        String regex = "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }


}
